package com.example.admin.uibestpractice;

import android.annotation.SuppressLint;
import android.content.AsyncQueryHandler;
import android.net.wifi.aware.DiscoverySession;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.zip.CheckedOutputStream;

public class SocketThread implements Runnable{
    private static final String TAG = "Socket:";
    public Handler revHandler;

    private Handler handler;

    private BufferedReader br;
    private OutputStream os;
    private Socket socket;

    public SocketThread(Handler handler) {
        this.handler = handler;
    }

    @SuppressLint("HandlerLeak")
    @Override
    public void run() {

        socket = new Socket();
        try {
            socket = new Socket("120.79.227.59", 2333);
            br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
            os = socket.getOutputStream();

            new Thread() {
                @Override
                public void run() {
                    try {
                        String line;
                        while ((line = br.readLine()) != null) {
                            Log.i(TAG, "读取数据：" + line);

                            Message message = new Message();
                            message.what = 1;
                            message.obj = line;

                            handler.sendMessage(message);

                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();

            Looper.prepare();
            revHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    try {
                        os.write((Build.MODEL + ":" + (msg.obj) + "\n").getBytes("utf-8"));

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
            Looper.loop();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
